package com.nowoe.server.http;

import com.nowoe.server.constant.Http;
import com.nowoe.server.util.HttpProtocolUtil;
import com.nowoe.server.util.StaticResourceUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author 倚栏听风 2024/1/5 15:13
 */
public class Response {
    private OutputStream outputStream;

    public Response() {
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public void output(String content) throws IOException {
        outputStream.write(content.getBytes());
    }

    public void outSuccess(String content) throws IOException {
        output(HttpProtocolUtil.getHttpHeader(Http.SUCCESS, content.getBytes().length) + content);
    }

    public void outputHtml(String path) throws IOException {
        String absolutePath = StaticResourceUtil.getAbsolutePath(path);
        File file = new File(absolutePath);
        if (file.exists() && file.isFile()) {
            StaticResourceUtil.outputStaticResource(new FileInputStream(file), outputStream);
        } else {
            output(HttpProtocolUtil.getHttpHeader(Http.NOT_FOUND, 0));
        }
    }
}
